package demo;
//定时器

import java.util.concurrent.PriorityBlockingQueue;

class MyTimer{

    //Task类来描述任务
    static class Task implements Comparable<Task>{
        private Runnable runnable;
        private long time;

        public Task(Runnable runnable, long after) {
            this.runnable = runnable;
            this.time = System.currentTimeMillis()+time;
        }
        public void run(){
            runnable.run();
        }

        @Override
        public int compareTo(Task o) {
            return (int)(this.time-o.time);
        }
    }

    //阻塞优先级队列
    private PriorityBlockingQueue<Task> tasks=new PriorityBlockingQueue<>();

    //插入任务
    public void schedule(Runnable runnable,long after){
        Task task=new Task(runnable,after);
        tasks.put(task);
    }

    //锁
    private Object locker=new Object();

    //定时器（在类加载时就进行的构造方法），创建一个线程检查当前队头任务距离开始执行的时间
    public MyTimer(){
        Thread t=new Thread(()->{
            try {
                Task task=tasks.take();
                long curTime=System.currentTimeMillis();
                if(task.time>curTime){
                    tasks.put(task);
                    synchronized (locker){
                        locker.wait(task.time-curTime);
                    }
                }else{
                    task.run();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t.start();
    }
}
public class Demo1 {
    public static void main(String[] args) {

    }
}
